package com.attilax.lang;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


//import com.attilax.core;
import com.attilax.text.regExpress;
import com.attilax.text.strUtil;
import com.attilax.web.ReqX;

public class ParamX {

	public static void main(String[] args) {
	String s="boxsys=http://192.168.0.111/lime/com.attilax.php/lang/api.php?iocx=iocx_timer&method=setTime&no=1&timex=@timex&movie=@movie;";
Map m=new HashMap(){
	{
		this.put("movie","aaaaaaaaa");
		this.put("timex","6000");
	}
};
//System.out.println("----:"+  core.toJsonStrO88( new ParamX().findSqlParam(s))  );
	System.out.println( new ParamX(). sqlFmt(s,m));
	}
	
	@Deprecated
	public List<String> findSqlParam(String sql)
	  {
		
		List<String> li=strUtil.  preg_match_all(regExpress.ParamNameExpress, sql);
		    //  print_r( $a);
		//     $GLOBALS["varsx"]["sql params"]=$a;
		  return li;
	  }
	
	public List<String> findSqlParamV2(String sql)
	  {
		
		List<String> li=strUtil.  preg_match_all(regExpress.ParamNameExpress4sql, sql);
		    //  print_r( $a);
		//     $GLOBALS["varsx"]["sql params"]=$a;
		  return li;
	  }
	  
	public String sqlFmt(String sql,Map s_GET)
	  {
		  List<String> params=findSqlParam(sql);
		  for (String p : params) {
			  String http_para_name=com.attilax.lang.text.strUtil. str_replace("@","",p);
			  if(s_GET.get(http_para_name) !=null) {
				String string = s_GET.get(http_para_name).toString();
				sql=com.attilax.lang.text.strUtil.str_replace(p,string,sql);
			}
			
		}
//		  foreach( $params as $p)
//		  {
//			
//		  }
		  return sql;  
		  
	  }
	
	public String sqlFmtV2(String sql,Map s_GET)
	  {
		  List<String> params=findSqlParamV2(sql);
		  for (String p : params) {
			  String http_para_name=com.attilax.lang.text.strUtil. str_replace("$","",p);
			  if(s_GET.get(http_para_name) !=null) {
				String string = s_GET.get(http_para_name).toString();
				sql=com.attilax.lang.text.strUtil.str_replace(p,string,sql);
			}
			
		}
//		  foreach( $params as $p)
//		  {
//			
//		  }
		  return sql;  
		  
	  }


	public Map urlParams2Map(String params) {
		Map o=new HashMap();
		String[] a=params.split("&");
		for(int i=0;i<a.length;i++)	
		{
			String itemx=a[i];
			String[] a2=itemx.split("=");
			String k=a2[0];
			String v = null;
			try {
				v = URLDecoder.decode(a2[1], "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch(Exception e){}
		o.put(k, v);
		}
		return o;
		 
	}


	public static String sqlFmt(String $sql, HttpServletRequest $_GET) {
		return	new ParamX().sqlFmtV2($sql, ReqX.toMap($_GET));
		// null;
	}

}
